var express = require("express");
var router = express.Router();
var Token = require("../Token.js");
const conn = require("../mysql/index.js");
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});
// 登录接口
router.post("/login", function (req, res, next) {
  let { username, password } = req.body;
  // 执行select查询语句, 返回的是数组;
  try {
    conn.query(
      "SELECT * FROM users WHERE username = ?",
      [username],
      (err, results) => {
        if (results.length > 0 && password == results[0].password) {
          const id = results[0].id;
          const token = Token.en(id);
          res.send({
            msg: "登录成功",
            data: {
              token: token,
            },
            code: 200,
          });
        } else {
          res.send({
            msg: "账号或密码错误请重新输入",
            code: 400,
          });
        }
      }
    );
  } catch (err) {
    res.send(err);
  }
});

module.exports = router;
